package com.intramirror.product.schedule;

import com.intramirror.product.controller.price.ProductDiscountByJobController;
import com.intramirror.product.mapper.AlgorithmOperationMapper;
import com.intramirror.product.schedule.consumer.CalculatePrdPrePriceConsumer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created on 2018/6/13.
 *
 * @author yfding
 */
@Service
public class BurstingManager {

    public static final Logger logger = LoggerFactory.getLogger(BurstingManager.class);

    @Autowired
    private AlgorithmOperationMapper algorithmOperationMapper;

    @Autowired
    private ProductDiscountByJobController productDiscountByJobController;

    @Autowired
    private CalculatePrdPrePriceConsumer calculatePrdPrePriceConsumer;

    public void refreshByDate(Date date) {
        if(date == null) {
            this.refresh();
            return;
        }
//        String start = getTimeByMinute(date, 15);
        String lastTime = DateFormatUtils.format(date, "yyyy-MM-dd HH:mm:ss");
        Integer count = algorithmOperationMapper.getBurstingUpdateCount(lastTime);
        logger.info("BurstingManager.refreshByDate,date:{},count:{}", date, count);
        if (count.intValue() == 1) {
            this.refresh();
        }
    }

    private void refresh() {
        synchronized (BurstingManager.class) {
            long start = System.currentTimeMillis();
            List<Long> productIds = algorithmOperationMapper.getBurstingProductIds();
            int i = 0;
            for (Long productId : productIds) {
                i++;
                try {
                    productDiscountByJobController.updateProductDiscountById(productId);
                    calculatePrdPrePriceConsumer.dealPreBoutique2ImDiscount(productId);
                    logger.info("BurstingManager.refresh,productId:{}", productId);
                    logger.info("BurstingManager.refresh,index:{}", i);

                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("BurstingManager.refresh,error:{}", e);
                }
            }
            long end = System.currentTimeMillis();
            logger.info("BurstingManager,refresh,start:" + start + ",end:" + end + ",time:" + (end - start));
        }
    }

    private String getTimeByMinute(Date date, int minute) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE) - minute);
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(calendar.getTime());
    }

}
